package com.heixiu.gallery2

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.*
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import kotlinx.android.synthetic.main.fragment_gallery.*

/**
 * A simple [Fragment] subclass.
 */
class GalleryFragment : Fragment() {
    private var dyNum  = 0
    private val galleryViewModel by viewModels<GalleryViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_gallery, container, false)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater.inflate(R.menu.overflow_menu, menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId) {
            R.id.overflowRefresh -> {
                swipeRefreshLayout.isRefreshing = true
                Handler().postDelayed(Runnable { galleryViewModel.resetData() }, 1000)
            }
        }
        return super.onOptionsItemSelected(item)
    }


    @SuppressLint("RestrictedApi")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        setHasOptionsMenu(true)

        with(floatingActionButtonToTop) {
            visibility = View.INVISIBLE
            setOnClickListener {
                dyNum = 0
                it.visibility = View.INVISIBLE
                recyclerView.scrollToPosition(0)
            }
        }

        // ViewModel以前的实例化方式
        //galleryViewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(requireActivity().application)).get(GalleryViewModel::class.java)

        val galleryAdapter = GalleryAdapter(galleryViewModel)
        recyclerView.apply {
            adapter = galleryAdapter
            //layoutManager = GridLayoutManager(requireContext(), 2)
            layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        }

        // 监听列表滚动
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                dyNum += dy
                if (dyNum > 600) {
                    floatingActionButtonToTop.visibility = View.VISIBLE
                } else {
                    floatingActionButtonToTop.visibility = View.INVISIBLE
                }

                if (dy >= 0) { // 上滑dy>=0，下滑dy<=0
                    val layoutManager = recyclerView.layoutManager as StaggeredGridLayoutManager
                    val intArray = IntArray(2)
                    layoutManager.findLastVisibleItemPositions(intArray)
                    if (intArray[0] == galleryAdapter.itemCount - 1) {
                        Handler().postDelayed(Runnable { galleryViewModel.fetchData() }, 1000)
                    }
                }
            }
        })

        // 监听数据改变
        galleryViewModel.photoList.observe(viewLifecycleOwner, Observer {
            if (galleryViewModel.scrollToTop) {
                recyclerView.scrollToPosition(0)
                galleryViewModel.scrollToTop = false
            }
            galleryAdapter.submitList(it)
            swipeRefreshLayout.isRefreshing = false
        })

        // 监听数据请求的状态
        galleryViewModel.requestState.observe(viewLifecycleOwner, Observer {
            galleryAdapter.requestState = it
            galleryAdapter.notifyItemChanged(galleryAdapter.itemCount - 1)
            if (it == GALLERY_REQUEST_NETWORK_ERROR) swipeRefreshLayout.isRefreshing = false
        })

        // 首次加载数据
        galleryViewModel.photoList.value ?: galleryViewModel.resetData()

        // 下拉刷新
        swipeRefreshLayout.setOnRefreshListener {
            Handler().postDelayed(Runnable { galleryViewModel.resetData() }, 1000)
        }
    }
}
